package com.alipay.zxy.alipayplugin.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayUserAgreementQueryModel;
import com.alipay.api.request.AlipayUserAgreementQueryRequest;
import com.alipay.api.response.AlipayUserAgreementQueryResponse;
import com.alipay.zxy.alipayplugin.config.AlipayConfig;
import com.alipay.zxy.alipayplugin.config.DefaultAlipayClientFactory;
import com.alipay.zxy.alipayplugin.message.response.AlipayUserAgreementQueryDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zxy
 */
@Slf4j
@Service
public class AlipayUserAgreementQueryService extends BaseService {

    private final AlipayConfig alipayConfig;

    @Autowired
    public AlipayUserAgreementQueryService(AlipayConfig alipayConfig) {
        this.alipayConfig = alipayConfig;
    }

    public AlipayUserAgreementQueryDTO query(AlipayUserAgreementQueryModel alipayModel) throws AlipayApiException {
        AlipayUserAgreementQueryDTO agreementQueryDTO;
        AlipayUserAgreementQueryRequest alipayRequest = new AlipayUserAgreementQueryRequest();
        alipayModel.setPersonalProductCode("GENERAL_WITHHOLDING_P");
        alipayRequest = (AlipayUserAgreementQueryRequest) getAlipayRequest(alipayRequest, alipayConfig, alipayModel);
        AlipayClient alipayClient = DefaultAlipayClientFactory.getInstance(alipayConfig);
        AlipayUserAgreementQueryResponse alipayResponse = alipayClient.execute(alipayRequest);
        if (alipayResponse.isSuccess()) {
            log.info("用户签约查询 alipayResponse:{}", JSONObject.toJSONString(alipayResponse));
            agreementQueryDTO = new AlipayUserAgreementQueryDTO();
            agreementQueryDTO.setAgreementNo(alipayResponse.getAgreementNo());
            agreementQueryDTO.setAlipayUserId(alipayResponse.getAlipayLogonId());
            agreementQueryDTO.setExternalLogonId(alipayResponse.getExternalLogonId());
            agreementQueryDTO.setInvalidTime(alipayResponse.getInvalidTime());
            return agreementQueryDTO;
        } else {
            log.info("支付宝签约查询错误 alipayResponse:{}", JSONObject.toJSONString(alipayResponse));
            return null;
        }
    }
}
